<template>
  <div
    class="receipt-order-edit-wrapper app-container"
    style="margin-bottom: 60px"
    v-loading="loading"
  >
    <el-card header="基本信息">
      <el-row :gutter="10" type="flex" class="info-row">
        <!-- 订单编号信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>订单编号: </span>
            <span>{{ headerList.vbillcode }}</span>
          </div>
        </el-col>

        <!-- 订单类型ID信息 -->
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>订单类型ID: </span>
            <span>{{ headerList.ctrantypeid }}</span>
          </div>
        </el-col> -->

        <!-- 采购订单主键信息 -->
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>采购订单主键: </span>
            <span>{{ headerList.pk_order }}</span>
          </div>
        </el-col> -->

        <!-- 订单类型编码信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>订单类型编码: </span>
            <span>{{ headerList.vtrantypecode }}</span>
          </div>
        </el-col>

        <!-- 审批时间信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>审批时间: </span>
            <span>{{ formatDate(headerList.taudittime) }}</span>
          </div>
        </el-col>

        <!-- 制单时间信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>制单时间: </span>
            <span>{{ formatDate(headerList.dmakedate) }}</span>
          </div>
        </el-col>

        <!-- 供应商相关信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>供应商编码: </span>
            <span>{{ headerList.pk_supplier.code }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span>供应商名称: </span>
            <span>{{ headerList.pk_supplier.name }}</span>
          </div>
        </el-col>
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>供应商主键: </span>
            <span>{{ headerList.pk_supplier.pk }}</span>
          </div>
        </el-col> -->

        <!-- 部门相关信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>部门编码: </span>
            <span>{{ headerList.pk_dept.code }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span>部门名称: </span>
            <span>{{ headerList.pk_dept.name }}</span>
          </div>
        </el-col>
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>部门主键: </span>
            <span>{{ headerList.pk_dept.pk }}</span>
          </div>
        </el-col> -->

        <!-- 员工相关信息 -->
        <el-col :span="8">
          <div class="info-item">
            <span>员工编码: </span>
            <span>{{ headerList.cemployeeid.code }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span>员工名称: </span>
            <span>{{ headerList.cemployeeid.name }}</span>
          </div>
        </el-col>
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>员工主键: </span>
            <span>{{ headerList.cemployeeid.pk }}</span>
          </div>
        </el-col> -->

        <!-- 总数量信息 -->
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>总数量: </span>
            <span>{{ headerList.ntotalastnum }}</span>
          </div>
        </el-col> -->

        <!-- 仓库信息 -->
        <!-- <el-col :span="8">
          <div class="info-item">
            <span>仓库: </span>
            <span>{{ headerList.cwarehouseid }}</span>
          </div>
        </el-col> -->
      </el-row>
    </el-card>

    <!-- 商品明细部分简化，去掉单选相关逻辑 -->
    <el-card header="商品明细" class="mt10">
      <div class="receipt-order-content">
        <el-row
          :gutter="10"
          class="flex-space-between mb8"
          type="flex"
          justify="space-between"
        >
          <el-col :span="6">
            <div>
              <span>单据信息 | 提交：</span>
            </div>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleDocAdd()">
              整单入库
            </el-button>
          </el-col> -->
        </el-row>
        <el-table :data="detailsList" border>
          <el-table-column
            prop="crowno"
            label="行号"
            align="center"
            sortable
            :sort-method="sortNumber"
            width="75"
          />
          <el-table-column label="物料信息" align="center">
            <template #default="{ row }">
              <div v-if="row.pk_material">编码：{{ row.pk_material.code }}</div>
              <div v-if="row.pk_material">名称：{{ row.pk_material.name }}</div>
              <!-- <div v-if="row.pk_material">主键：{{ row.pk_material.pk }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="物料管理信息" align="center">
            <template #default="{ row }">
              <div v-if="row.additionMap">
                GMP码：{{ row.additionMap.graphid }}
              </div>
              <div v-if="row.additionMap">
                规格：{{ row.additionMap.materialtype }}
              </div>
              <div v-if="row.additionMap">型号：{{ row.additionMap.spec }}</div>
            </template>
          </el-table-column>
          <el-table-column label="生产厂商信息" align="center">
            <template #default="{ row }">
              <div v-if="row.cproductorid">
                编码：{{ row.cproductorid.code }}
              </div>
              <div v-if="row.cproductorid">
                名称：{{ row.cproductorid.name }}
              </div>
              <!-- <div v-if="row.cproductorid">主键：{{ row.cproductorid.pk }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="单位信息" align="center">
            <template #default="{ row }">
              <div v-if="row.castunitid">编码：{{ row.castunitid.code }}</div>
              <div v-if="row.castunitid">名称：{{ row.castunitid.name }}</div>
              <!-- <div v-if="row.castunitid">主键：{{ row.castunitid.pk }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="主单位信息" align="center">
            <template #default="{ row }">
              <div v-if="row.cunitid">编码：{{ row.cunitid.code }}</div>
              <div v-if="row.cunitid">名称：{{ row.cunitid.name }}</div>
              <!-- <div v-if="row.cunitid">主键：{{ row.cunitid.pk }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="财务组织信息" align="center">
            <template #default="{ row }">
              <div v-if="row.pk_psfinanceorg_v">
                编码：{{ row.pk_psfinanceorg_v.code }}
              </div>
              <div v-if="row.pk_psfinanceorg_v">
                名称：{{ row.pk_psfinanceorg_v.name }}
              </div>
              <!-- <div v-if="row.pk_psfinanceorg_v">主键：{{ row.pk_psfinanceorg_v.pk }}</div> -->
            </template>
          </el-table-column>
          <!-- <el-table-column prop="nnum" label="实收主数量" /> -->
          <!-- <el-table-column prop="nastnumnshouldnnum" label="数量" /> -->
          <!-- <el-table-column prop="nshouldnnum" label="应收主数量" /> -->
          <el-table-column prop="vchangerate" label="换算率" align="center" />
          <el-table-column label="是否关闭库存" align="center">
            <template #default="{ row }">
              {{ row.bstockclose === "Y" ? "是" : "否" }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="pk_order_b" label="采购订单明细" align="center" /> -->
          <el-table-column label="单据日期" align="center">
            <template #default="{ row }">{{
              formatDate(row.dbilldate)
            }}</template>
          </el-table-column>
          <el-table-column label="计划到货日期" align="center">
            <template #default="{ row }">{{
              formatDate(row.dplanarrvdate)
            }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <!-- 使用 el-tooltip 显示提示信息 -->
              <!-- <el-tooltip v-if="row.bstockclose === 'N'" content="库存已关闭，无法点击新增" placement="top">
                <el-button type="primary" plain icon="Plus" :disabled="row.bstockclose === 'N'"
                  @click="handleDocAdd(row)">
                  单据入库
                </el-button>
              </el-tooltip>
              <el-button v-else type="primary" plain icon="Plus" @click="handleDocAdd(row)">
                单据入库
              </el-button> -->
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleDocAdd(row)"
              >
                单据入库
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 打开嵌套表单的 Dialog -->
    <el-dialog
      title="入库信息单"
      :visible.sync="dialogFormVisible"
      append-to-body
      width="90%"
      :close-on-click-modal="false"
    >
      <!-- 仓库信息 -->
      <el-form
        ref="elForm"
        :model="headerList"
        :rules="rules"
        size="medium"
        label-width="65px"
      >
        <el-col :span="12">
          <el-form-item label="仓库:" prop="cwarehouseid">
            <el-select
              v-model="headerList.cwarehouseid"
              placeholder="请选择下拉选择"
              :style="{ width: '100%' }"
              :disabled="true"
            >
              <el-option
                v-for="(item, index) in NccStockOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 新增同步数量按钮 -->
        <!-- <el-col :span="12" style="text-align: right">
          <el-button type="primary" plain @click="syncQuantities">同步数量</el-button>
        </el-col> -->
      </el-form>

      <el-form
        ref="elDialogForm"
        :model="detailsData"
        label-width="10px"
        :rules="rules"
      >
        <el-table
          ref="mainTable"
          :data="allRowsForDocAdd ? detailsList : [selectedRowForDocAdd]"
          border
          @selection-change="handleTableSelectionChange"
          label-position="top"
          :row-key="(row) => row.crowno"
          :key="
            (allRowsForDocAdd ? 'allRows' : 'singleRow') +
            '-' +
            detailsList.map((item) => item.crowno).join('-')
          "
        >
          <!-- 正式表格行下面隐藏的内容 -->
          <el-table-column type="expand" width="35">
            <el-table
              :data="batchCodeList"
              border
              style="width: 96%; margin: 0 auto; min-height: 100px"
              @row-click="handleRowClick"
            >
              <el-table-column label="药品名称" align="center">
                <template #default="{ row }">{{ row.name }}</template>
              </el-table-column>
              <el-table-column label="药品PK" align="center">
                <template #default="{ row }">{{ row.pk_material }}</template>
              </el-table-column>
              <el-table-column label="仓库" align="center">
                <template #default="{ row }">{{
                  row.cwarehouse_name
                }}</template>
              </el-table-column>
              <el-table-column label="状态" align="center">
                <template #default="{ row }">{{ row.SkuState }}</template>
              </el-table-column>
              <el-table-column label="批号" align="center">
                <template #default="{ row }">{{ row.vbatchcode }}</template>
              </el-table-column>
              <el-table-column label="供应商批号" align="center">
                <template #default="{ row }">{{ row.vvendbatchcode }}</template>
              </el-table-column>
              <!-- <el-table-column label="供应商" align="center">
                <template #default="{ row }">{{ row.sender_name }}</template>
              </el-table-column> -->
              <el-table-column label="数量信息">
                <template #default="{ row }">
                  <div>数量：{{ row.sku_num }}</div>
                  <div>可用数量：{{ row.use_num }}</div>
                  <div>冻结数量：{{ row.freeze_num }}</div>
                  <div>在途数量：{{ row.enable_num }}</div>
                </template>
              </el-table-column>
              <el-table-column label="生产日期" align="center">
                <template #default="{ row }">{{ row.exp_date }}</template>
              </el-table-column>
              <el-table-column label="有效期" align="center">
                <template #default="{ row }">{{ row.exp_date }}</template>
              </el-table-column>
              <el-table-column label="复验期" align="center">
                <template #default="{ row }">{{
                  row.retest_date === "1900-01-01 00:00:00"
                    ? null
                    : row.retest_date
                }}</template>
              </el-table-column>
              <el-table-column label="生产厂商" align="center">
                <template #default="{ row }">{{ row.product_name }}</template>
              </el-table-column>
              <el-table-column label="包材版本" align="center">
                <template #default="{ row }">{{ row.vbcdef3 }}</template>
              </el-table-column>
            </el-table>
          </el-table-column>
          <!-- 选择框列 -->
          <el-table-column
            label="行号"
            sortable
            :sort-method="sortNumber"
            width="75"
          >
            <template #default="{ row }">
              <div>{{ row.crowno }}</div>
            </template>
          </el-table-column>
          <el-table-column label="物料信息">
            <template #default="{ row }">
              <div>物料编码：{{ row.pk_material.code }}</div>
              <div>物料名称：{{ row.pk_material.name }}</div>
              <div>物料主键：{{ row.pk_material.pk }}</div>
              <div>批次号主键：{{ row.pk_batchcode }}</div>
            </template>
          </el-table-column>
          <el-table-column label="物料管理信息">
            <template #default="{ row }">
              <div>GMP码：{{ row.additionMap.graphid }}</div>
              <div>规格：{{ row.additionMap.materialtype }}</div>
              <div>型号：{{ row.additionMap.spec }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="dplanarrvdate" label="计划到货日期" />
          <!-- 数量信息 -->
          <el-table-column label="数量信息">
            <template #default="{ row }">
              <div>
                <span>应收主数量：</span>
                <span>{{ row.nshouldnnum }}</span>
                <span>&nbsp;({{ row.cunitid.name }})</span>
              </div>
              <div>
                <span>应收辅数量：</span>
                <span>{{ calculateShouldAssistNum(row) }}</span>
                <span>&nbsp;({{ row.castunitid.name }})</span>
              </div>
              <div>
                <i class="mark-red"></i>
                <span>实收主数量：</span>
                <el-input
                  v-model="row.nnum"
                  placeholder="请输入实收主数量"
                  clearable
                  @input="calculateAssistNum(row)"
                ></el-input>
              </div>
              <div>
                <span>实收辅数量：</span>
                <el-input
                  v-model="row.nassistnum"
                  placeholder="请输入实收辅数量"
                  clearable
                  readonly
                ></el-input>
                <!-- readonly：将输入框设置为只读状态，用户可以看到内容，但不能修改 -->
              </div>
              <div>
                <span>容器：</span>
                <el-input
                  v-model="row.vbdef50"
                  placeholder="请输入容器"
                  clearable
                ></el-input>
              </div>
            </template>
          </el-table-column>
          <!-- 库存信息 -->
          <el-table-column label="库存信息">
            <template #default="{ row }">
              <div>
                <i class="mark-red"></i>
                <span>仓库：</span>
                <el-select
                  v-model="row.cwarehouseid"
                  placeholder="请选择下拉选择"
                  :style="{ width: '100%' }"
                  :disabled="row.bstockclose === 'Y' || true"
                  @change="handleCwarehouseChange"
                >
                  <el-option
                    v-for="(item, index) in NccStockOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
              <div>
                <span>库存状态：</span>
                <el-select
                  v-model="row.cstateid"
                  placeholder="请选择下拉选择"
                  size="small"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                >
                  <el-option
                    v-for="(item, index) in NccStatusOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
              <!-- 这里的两个值是必须要传的 -->
              <div>
                <span>WMS库房ID：</span>
                <span>{{ row.sto_id }}</span>
              </div>
              <div>
                <span>WMS库房商品分类ID：</span>
                <span>{{ row.stu_class_id }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- 批号信息 -->
          <el-table-column label="批号信息">
            <template #default="{ row }">
              <div>
                <span>供应商批号：</span>
                <el-input
                  v-model="row.vvendbatchcode"
                  placeholder="请输入供应商批号"
                  clearable
                  :disabled="true"
                ></el-input>
              </div>
              <div>
                <span>供应商代码：</span>
                <el-input
                  v-model="row.vbcdef2"
                  placeholder="请输入供应商代码"
                  clearable
                  :disabled="true"
                ></el-input>
              </div>
              <div>
                <span>包材版本：</span>
                <el-input
                  v-model="row.vbcdef3"
                  placeholder="请输入包材版本"
                  clearable
                  :disabled="true"
                ></el-input>
              </div>
              <div>
                <!-- 自定义批号 -->
                <i class="mark-arrow"></i>
                批次号：
                <el-input
                  v-model="row.vbatchcode"
                  placeholder="请输入批号"
                  clearable
                  @input="handleBatchCodeChange(row)"
                  @blur="validateBatchNoUniqueness(row)"
                />
              </div>
            </template>
          </el-table-column>
          <!-- 时间信息 -->
          <el-table-column label="时间信息">
            <template #default="{ row }">
              <div>
                <span>生产日期：</span>
                <el-date-picker
                  v-model="row.dproducedate"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择生产日期"
                  clearable
                  :style="{ width: '100%' }"
                  disabled
                >
                </el-date-picker>
              </div>
              <div>
                <span>有效期：</span>
                <el-date-picker
                  v-model="row.dvalidate"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择有效期"
                  clearable
                  :style="{ width: '100%' }"
                  disabled
                >
                </el-date-picker>
              </div>
              <div>
                <span>复验期：</span>
                <el-date-picker
                  v-model="row.vbdef48"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择复验期"
                  clearable
                  :style="{ width: '100%' }"
                  disabled
                >
                </el-date-picker>
              </div>
              <div>
                <span>货架期：</span>
                <el-date-picker
                  v-model="row.vbdef49"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择货架期"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-date-picker>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            type="selection"
            width="55"
            :reserve-selection="true"
            :selectable="isSelectable"
          />
        </el-table>

        <el-form-item
          size="large"
          style="margin-top: 20px; display: flex; justify-content: flex-end"
        >
          <el-button type="primary" @click="createPurchaseInboundOrderList()"
            >提交入库</el-button
          >
          <!-- <el-button @click="resetForm">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 获取NCC采购订单接口
import { getPurchaseNccInfo } from "@/api/storage/nccStore.js";
// 创建入库单
import { createPurchaseInboundOrder } from "@/api/storage/nccStore.js";
// 验证批次号是否唯一
import { getWMSCommonBatchNo } from "@/api/storage/nccStore.js";

// 根据获取NCC物料库存信息接口
import { getSelectNccMaterialInfo } from "@/api/public.js";

// 引入下拉框方法组件
import SearchSelect from "@/views/components/dropDown/searchSelect.js";
export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false, // 初始化loading属性为false
      isSubmitting: false, // 添加一个标志位来防止重复提交
      selectedRow: null, // 当前选中的表格行
      tableRowChecked: [], // 用于记录每行的选中状态
      nccList: {}, // NCC仓库信息
      nccStatusList: {}, // NCC库存状态信息
      headerList: {
        pk_supplier: {
          code: "",
          name: "",
          pk: "",
        },
        vbillcode: "",
        dbilldate: "",
        pk_dept: {
          code: "",
          name: "",
          pk: "",
        },
        ctrantypeid: "",
        pk_order: "",
        vtrantypecode: "",
        taudittime: null, // 初始化审批时间
        cemployeeid: {
          code: "",
          name: "",
          pk: "",
        },
        dmakedate: null, // 初始化制单时间
        ntotalastnum: "",
        cwarehouseid: "", // 仓库信息整合到headerList里
      },
      detailsList: [], // 商品明细信息（包含表格里各列对应的数据）
      dialogFormVisible: false,
      detailsData: {
        cstateid: "", // 库存状态
        nnum: "", // 实收主数量
        vvendbatchcode: "", // 供应商批号
        vbatchcode: "", // 批号
        dproducedate: "", // 生产日期
        dvalidate: "", // 有效期
        vbdef48: "", // 复验期
        vbdef49: "", // 货架期
        vbdef50: "", // 容器
        cwarehouseid: "", // 明细的仓库
        vbcdef2: "", // 供应商代码
        vbcdef3: "", // 包材版本
        pk_batchcode: "", // 批次号主键 --- 做负单的时候必须要
        parent_class_id: "", // 商品类型
        sto_id: "", // WMS库房ID
        stu_class_id: "", // WMS库房商品分类ID
      },
      rules: {
        pk_supplier: [],
        vbillcode: [],
        ctrantypeid: [],
        pk_order: [],
        vtrantypecode: [],
        taudittime: [],
        cemployeeid: [],
        dmakedate: [],
        ntotalastnum: [],

        // 仓库主键 以下为弹出框的内容
        cwarehouseid: [
          {
            required: true, // 添加必填验证
            message: "仓库不能为空，请选择仓库", // 验证不通过时显示的提示信息
            trigger: "change", // 触发验证的时机，当下拉框选项改变时触发验证
          },
        ],
        cstateid: [], // 库存状态
        nnum: [], // 实收主数量
        vvendbatchcode: [], // 供应商批号
        vbatchcode: [], // 批号
        dproducedate: [], // 生产日期
        dvalidate: [], // 有效期
        vbdef48: [], // 复验期
        vbdef49: [], // 货架期
        vbdef50: [], // 容器
      },
      NccStockOptions: [], // 仓库主键
      NccStatusOptions: [], // 库存状态
      nnumOptions: [], // 实收主数量
      vvendbatchcodeOptions: [], // 供应商批号
      vbatchcodeOptions: [], // 批号
      vbdef50Options: [], // 容器
      formData: {}, // 初始化formData为一个空对象，使其可以后续添加响应式属性
      allRowsForDocAdd: false,
      selectedRowForDocAdd: null,
      allowManualWarehouseSelection: false, // 重置允许手动选择仓库的标志位
      bstockclose: "Y", // 是否关闭库存,必须填Y,否则出不来单据信息
      batchCodeList: [], // 存储接口返回的数据
      selectedRow: null, // 用户选择的行数据
      modeType: "3", // 批次模式(批号模式 0：等于任意一个 1：等于 2：不等于 3：包含4：不包含)
      cachedCrowno: null, // 新增变量用于缓存行号

      batchNoValidationLoading: false, // 批次号验证相关状态
    };
  },
  watch: {
    dialogFormVisible(newValue) {
      if (!newValue) {
        // 当 dialogFormVisible 变为 false，即弹框关闭时
        this.queryPurchaseNccList();
      }
    },
  },

  created() {
    // 获取路由传递的参数
    this.vbillcode = this.$route.query.vbillcode;
    this.dbilldate = this.$route.query.dbilldate;

    if (!this.vbillcode) {
      this.$message.error("未接收到订单编号，请返回重试！");
    }
    if (!this.dbilldate) {
      this.$message.error("未接收到日期范围，请返回重试！");
    }
  },
  mounted() {
    this.queryPurchaseNccList(); // 查询NCC采购订单列表

    // 确保 tableRowChecked 数组初始化正确
    this.tableRowChecked = new Array(this.detailsList.length).fill(false);
    // 打印 detailsList 中元素的 id 情况进行查看
    this.detailsList.forEach((item, index) => {
      console.log(`第${index + 1}行元素的 id 为:`, item.id);
    });

    // this.getSelectNccMaterialInfoList(); // 获取NCC物料库存信息列表

    this.searchNCCStockList(); // 1、获取NCC仓库信息
    this.searchNCCStockStatusList(); //2、获取NCC库存状态信息
  },
  methods: {
    
    /**
     * 验证批次号唯一性
     * @param {Object} row - 当前行数据
     */
    async validateBatchNoUniqueness(row) {
      // 跳过空值验证
      if (!row.vbatchcode.trim()) {
        this.$set(row, "batchNoError", false);
        return;
      }

      // 显示加载状态
      this.batchNoValidationLoading = true;

      try {
        // 调用批次号唯一验证接口
        const response = await getWMSCommonBatchNo(row.vbatchcode);

        // 处理接口返回结果（假设接口返回true表示重复，false表示唯一）
        if (response.data) {
          // 批次号重复
          this.$set(row, "batchNoError", true);
          await this.$confirm(
            `批次号 "${row.vbatchcode}" 已存在，请重新输入`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          );
          // 清空批次号输入框
          this.$set(row, "vbatchcode", "");
        } else {
          // 批次号唯一
          this.$set(row, "batchNoError", false);
        }
      } catch (error) {
        console.error("批次号验证失败", error);
        this.$message.error("批次号验证失败，请稍后再试");
      } finally {
        // 隐藏加载状态
        this.batchNoValidationLoading = false;
      }
    },

    // 实现行号的数值升序排序（解决"1,10,2"等字符串排序异常问题）
    sortNumber(a, b) {
      return Number(a.crowno) - Number(b.crowno);
    },
    // 格式化时间
    formatDate(date) {
      if (!date) return ""; // 如果 `date` 为空或 `null`，返回占位符
      return this.$dayjs(date).isValid()
        ? this.$dayjs(date).format("YYYY-MM-DD")
        : "-";
    },
    // 同步数量方法
    // syncQuantities() {
    //   // 判断是整单入库还是单行入库
    //   if (this.allRowsForDocAdd) {
    //     // 整单入库，遍历所有行
    //     this.detailsList.forEach(row => {
    //       this.$set(row, 'nnum', row.nshouldnnum);
    //       // 同步后重新计算实收辅数量
    //       this.calculateAssistNum(row);
    //     });
    //   } else if (this.selectedRowForDocAdd) {
    //     const row = this.selectedRowForDocAdd;
    //     this.$set(row, 'nnum', row.nshouldnnum);
    //     // 同步后重新计算实收辅数量
    //     this.calculateAssistNum(row);
    //   }
    //   this.$forceUpdate(); // 强制更新视图
    // },

    // 实收主数量与实收辅数量转换
    // calculateAssistNum(row) {
    //   // 如果实收主数量为空，则将实收辅数量置为空
    //   if (!row.nnum || row.nnum === '') {
    //     row.nassistnum = ''; // 确保清空辅数量
    //     return;
    //   }

    //   // 转换主数量为浮点数
    //   const mainNum = parseFloat(row.nnum);

    //   // 判断输入的实收主数量是否为负数
    //   if (mainNum >= 0) {
    //     this.$message({
    //       message: '实收主数量必须为负数',
    //       type: 'warning'
    //     });
    //     row.nnum = ''; // 将主数量重置为空
    //     row.nassistnum = ''; // 清空辅数量
    //     return;
    //   }

    //   // 判断是否超过应收主数量
    //   const shouldMainNum = parseFloat(row.nshouldnnum);
    //   if (mainNum > shouldMainNum) {
    //     this.$message({
    //       message: '实收主数量不能超过应收主数量',
    //       type: 'warning'
    //     });
    //     // 恢复到应收主数量
    //     row.nnum = shouldMainNum;
    //     return;
    //   }

    //   // 检查转换率是否有效
    //   const changerateArr = row.vchangerate.split('/');
    //   const factor = parseFloat(changerateArr[1]) / parseFloat(changerateArr[0]);
    //   if (isNaN(factor)) {
    //     row.nassistnum = ''; // 如果转换率无效，清空辅数量
    //     return;
    //   }

    //   // 计算辅数量并更新
    //   row.nassistnum = (mainNum * factor).toFixed(0); // 这里保留两位小数，可按需调整
    // },

    calculateAssistNum(row) {
      // 如果实收主数量为空，则将实收辅数量置为空
      if (!row.nnum || row.nnum === "") {
        row.nassistnum = ""; // 确保清空辅数量
        return;
      }

      // 转换主数量为浮点数
      const mainNum = parseFloat(row.nnum);

      // 判断输入的实收主数量是否为负数
      if (mainNum >= 0) {
        this.$message({
          message: "实收主数量必须为负数",
          type: "warning",
        });
        row.nnum = ""; // 将主数量重置为空
        row.nassistnum = ""; // 清空辅数量
        return;
      }

      // 判断是否超过应收主数量
      const shouldMainNum = parseFloat(row.nshouldnnum);
      if (Math.abs(mainNum) > Math.abs(shouldMainNum)) {
        // 如果超过应收主数量，将实收主数量设置为应收主数量的负数
        row.nnum = `-${Math.abs(shouldMainNum)}`;
        this.$message({
          message: "实收主数量不能超过应收主数量",
          type: "warning",
        });
        row.nnum = ""; // 将主数量重置为空
        row.nassistnum = ""; // 清空辅数量
        return;
      }

      // 检查转换率是否有效
      const changerateArr = row.vchangerate.split("/");
      const factor =
        parseFloat(changerateArr[1]) / parseFloat(changerateArr[0]);
      if (isNaN(factor)) {
        row.nassistnum = ""; // 如果转换率无效，清空辅数量
        return;
      }

      // 计算辅数量并更新
      row.nassistnum = (mainNum * factor).toFixed(4); // 这里保留两位小数，可按需调整
    },

    // 应收主数量与应收辅数量转换
    calculateShouldAssistNum(row) {
      const changerateArr = row.vchangerate.split("/");
      const mainNum = parseFloat(row.nshouldnnum);
      const factor =
        parseFloat(changerateArr[1]) / parseFloat(changerateArr[0]);
      return (mainNum * factor).toFixed(4); // 这里保留两位小数，可按需调整
    },

    // 此方法在仓库选择下拉框的值发生改变时触发。
    // handleCwarehouseChange(value) {
    //   // 使用 Vue 的 $set 方法，确保 Vue 能够检测到对 headerList 对象中 cwarehouseid 属性的更改。
    //   this.$set(this.headerList, 'cwarehouseid', value);
    // },
    // 确保 row 的仓库选择发生变化时触发相关处理
    handleCwarehouseChange(row) {
      console.log("仓库选择变化", row);
      // 更新 headerList.cwarehouseid
      this.$set(this.headerList, "cwarehouseid", row.cwarehouseid);
      // 强制更新视图
      this.$forceUpdate();
    },

    /**
     * 用于处理“整单入库/单据入库”按钮的点击事件。
     * 此方法的主要作用是打开弹出对话框（由 dialogFormVisible 控制显示隐藏）。
     */
    handleDocAdd(row) {
      if (row) {
        // 单行入库
        this.selectedRowForDocAdd = row;
        this.allRowsForDocAdd = false;
        const wmsWareHouse = row.wmsWareHouse;
        if (wmsWareHouse === null) {
          // 如果wmsWareHouse为null，设置仓库信息下拉框必填验证
          this.rules.cwarehouseid = [
            {
              required: true,
              message: "仓库不能为空，请选择仓库",
              trigger: "change",
            },
          ];
          this.allowManualWarehouseSelection = true;
        } else {
          // 如果wmsWareHouse为其他值，使用$set设置headerList.cwarehouseid
          this.$set(this.headerList, "cwarehouseid", wmsWareHouse);
          // 移除必填验证
          this.rules.cwarehouseid = [];
          // 允许手动选择仓库
          this.allowManualWarehouseSelection = true;
        }
      } else {
        // 整单入库
        this.allRowsForDocAdd = true;
        const wmsWareHouseValues = this.detailsList.map(
          (item) => item.wmsWareHouse
        );
        const hasNull = wmsWareHouseValues.includes(null);
        const allSame = new Set(wmsWareHouseValues).size === 1 && !hasNull;

        if (hasNull) {
          this.$message.warning("当前单据不支持整单入库，请分批入库");
          this.allRowsForDocAdd = false;
          return;
        } else if (!allSame) {
          this.$message.warning(
            "当前单据多条明细入库仓库选择不一致，不支持整单入库，请分批入库"
          );
          this.allRowsForDocAdd = false;
          return;
        }
        const wmsWareHouse =
          this.detailsList.length > 0 ? this.detailsList[0].wmsWareHouse : null;
        if (wmsWareHouse === null) {
          // 如果wmsWareHouse为null，设置仓库信息下拉框必填验证
          this.rules.cwarehouseid = [
            {
              required: true,
              message: "仓库不能为空，请选择仓库",
              trigger: "change",
            },
          ];
          this.allowManualWarehouseSelection = true;
        } else {
          // 如果wmsWareHouse为其他值，使用$set设置headerList.cwarehouseid
          this.$set(this.headerList, "cwarehouseid", wmsWareHouse);
          // 移除必填验证
          this.rules.cwarehouseid = [];
          // 允许手动选择仓库
          this.allowManualWarehouseSelection = true;
        }
      }
      this.dialogFormVisible = true;
    },

    /**
     * 此方法用于控制el-table中每行是否可被选择，根据每行数据的业务状态决定选择框是否可用
     * 接收一个row参数，该参数为el-table中的行数据对象
     */
    isSelectable(row) {
      return row.bstockclose !== "Y";
      // return row.bstockclose !== 'N';
    },

    /**
     * 此方法处理点击“入库”按钮时的一系列业务逻辑，包括更新行选中状态、同步相关数据以及控制对话框显示等操作
     * 接收一个row参数，该参数代表点击“入库”按钮所在行的数据对象
     */
    handleWarehousingClick(row) {
      const rowIndex = this.detailsList.indexOf(row);
      if (rowIndex !== -1) {
        const table = this.$refs.inboundTable;
        if (table) {
          // 再次确认 row 是 detailsList 里的原始对象引用，保证 toggleRowSelection 能正确识别行
          const originalRow = this.detailsList.find((item) => item === row);
          if (originalRow) {
            table.toggleRowSelection(originalRow, true);
          }
        }
        // 更新 tableRowChecked 数组对应位置为 true，表示该行被选中
        this.tableRowChecked[rowIndex] = true;
        // 重新计算并更新 selectedRow 和 tableRowChecked 数据，确保状态一致性
        this.handleTableSelectionChange(
          this.detailsList.filter((_, index) => this.tableRowChecked[index])
        );
        if (row.bstockclose !== "N") {
          this.dialogFormVisible = true;
        } else {
          this.$message.warning("入库已关闭");
        }
      }
    },

    /**
     * 处理表格行选择事件，当用户选择/取消选择表头或某一行时触发
     * @param {Array} selectedRows - 当前选中的行数据数组
     */
    handleTableSelectionChange(selectedRows) {
      // 先验证传入的selectedRows参数是否是有效的数组
      if (!Array.isArray(selectedRows)) {
        console.error("传入的selectedRows参数不是一个有效的数组", selectedRows);
        return;
      }
      // 验证detailsList是否已经正确初始化且是数组
      if (!Array.isArray(this.detailsList)) {
        console.error(
          "this.detailsList未正确初始化，不是有效的数组",
          this.detailsList
        );
        return;
      }
      // 1. 遍历detailsList数据
      //    对于每一行数据，检查它是否包含在selectedRows中。
      // 2. 如果在selectedRows中，表示该行被选中，在tableRowChecked中标记为true；
      //    否则标记为false。
      this.tableRowChecked = this.detailsList.map((row) =>
        selectedRows.includes(row)
      );
      console.log(
        "handleTableSelectionChange方法中，detailsList的详细内容:",
        this.detailsList
      );

      if (this.allRowsForDocAdd) {
        // 直接将selectedRows整体赋给this.selectedRow，以支持多选情况，仅在整单入库时执行此操作
        this.selectedRow = selectedRows;

        // 检查整单中是否存在库存已关闭的行，若有则关闭对话框并提示用户
        const hasClosedStock = selectedRows.some(
          (row) => row.bstockclose === "N"
        );
        if (hasClosedStock) {
          this.dialogFormVisible = false;
          this.$message.warning("整单中存在库存已关闭的商品，无法进行入库操作");
        }
      }

      console.log("当前选中的行数据:", selectedRows);
      console.log("当前选中的状态数组:", this.tableRowChecked);
      console.log("当前选中行详细数据:", this.selectedRow);
    },

    /**
     * 创建入库单列表
     */
    createPurchaseInboundOrderList() {
      if (this.isSubmitting) {
        return; // 如果正在提交，直接返回，不执行后续代码
      }
      this.isSubmitting = true; // 设置正在提交的标志位

      this.loading = true;
      let selectedRows;
      if (this.allRowsForDocAdd) {
        // 整单入库，使用全部单据数据
        selectedRows = this.detailsList.filter(
          (_, index) => this.tableRowChecked[index]
        );

        // 检查所有选中行的仓库是否相同
        const warehouses = selectedRows.map((row) => row.cwarehouseid);
        const uniqueWarehouses = new Set(warehouses);
        if (uniqueWarehouses.size > 1) {
          this.$message.warning(
            "不同仓库，不能整单提交，请选择相同仓库进行提交"
          );
          this.loading = false;
          this.isSubmitting = false; // 重置标志位
          return;
        }
      } else {
        // 单据入库，只使用当前行数据
        selectedRows = [this.selectedRowForDocAdd];
      }

      // 以下代码保持不变
      const allSelectedRowData = [];
      selectedRows.forEach((selectedRow) => {
        allSelectedRowData.push({
          ...selectedRow,
        });
      });
      const header = this.headerList;
      // 移除仓库必填验证，允许不选择仓库提交
      // if (!header.cwarehouseid && !this.allowManualWarehouseSelection) {
      //   this.$message.error("仓库信息不能为空，请选择仓库后再提交");
      //   this.loading = false;
      //   this.isSubmitting = false; // 重置标志位
      //   return;
      // }
      const combinedData = {
        header,
        details: allSelectedRowData,
      };
      console.log("即将传递给接口的参数数据:", combinedData);
      // 调用封装的接口，并传入整合好的数据
      createPurchaseInboundOrder(combinedData)
        .then((response) => {
          console.log("接口请求成功，返回response数据：", response);

          this.loading = false;
          this.isSubmitting = false; // 重置标志位

          // 根据接口返回结果进行相应的业务处理，提示用户操作成功
          // 添加对code值的判断逻辑
          if (response.code === 200) {
            this.$message({
              message: response.msg,
              type: "success",
            });
            this.dialogFormVisible = false; // 关闭弹出框
            this.$tab.closePage(); // 关闭当前页面的标签

            // 跳转到收货管理页面
            this.$router.push('/wms/receive');
          } else {
            this.$message({
              message: response.msg,
              type: "error",
            });
          }
        })
        .catch((error) => {
          this.loading = false;
          this.isSubmitting = false; // 重置标志位
          console.log("接口请求出错:", error);
        });
    },

    /**
     * 查询NCC采购订单列表
     * 在queryPurchaseNccList方法中，获取数据后检查并处理唯一性
     */
    queryPurchaseNccList() {
      const params = {
        vbillcode: this.vbillcode,
        bstockclose: this.bstockclose,
        dbilldate: this.dbilldate,
      };
      console.log("params监控=", params);
      this.loading = true;
      getPurchaseNccInfo(params)
        .then((response) => {
          this.responseData = response.rows;
          if (response.rows.length > 0) {
            const header = response.rows[0].header;
            const details = response.rows[0].details;
            const pkSet = new Set();
            const processedDetails = details.filter((detail) => {
              if (!detail.pk_material) {
                detail.pk_material = {};
              }
              if (pkSet.has(detail.crowno)) {
                // 如果检测到重复，添加唯一标识，例如时间戳
                detail.crowno = `${detail.crowno}_${new Date().getTime()}`;
              } else {
                pkSet.add(detail.crowno);
              }
              return true;
            });
            this.$set(this, "headerList", header);
            this.detailsList = processedDetails;
            // 同步headerList的数据到formData
            //...
          } else {
            console.warn("返回数据为空");
          }
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
          console.log("接口请求出错:", error);
        });
    },

    // 批号变化时触发查询
    handleBatchCodeChange(row) {
      const params = {
        primaryKey: row.pk_material.pk,
        batchNo: row.vbatchcode,
        modeType: this.modeType,
      };
      console.log("批号变化时触发查询信息params：", params);
      this.cachedCrowno = row.crowno; // 缓存行号
      console.log("缓存行号-row.crowno：", row.crowno);
      this.getSelectNccMaterialInfoList(params, row);
      if (this.allRowsForDocAdd) {
        console.log(
          "整单入库时，当前行在detailsList中的索引:",
          this.detailsList.findIndex((r) => r === row)
        );
      }
    },
    // 获取库存信息并更新表单数据
    getSelectNccMaterialInfoList(params, targetRow) {
      this.loading = true;
      getSelectNccMaterialInfo(params)
        .then((response) => {
          console.log("接口请求成功，NCC物料库存信息：", response);
          if (response.code === 200) {
            const responseData = response.data;
            console.log("NCC物料库存信息responseData:", responseData);
            this.batchCodeList = responseData;

            // 以下代码是自动打开<el-table-column type="expand" width="35">表格行下面隐藏的内容的代码
            // if (responseData && responseData.length > 0) {
            //   this.$nextTick(() => {
            //     const allRows = this.allRowsForDocAdd ? this.detailsList : [this.selectedRowForDocAdd];
            //     const targetRowIndex = allRows.findIndex(row => row === targetRow);
            //     if (targetRowIndex !== -1 && this.$refs.mainTable) {
            //       this.$refs.mainTable.toggleRowExpansion(allRows[targetRowIndex], true);
            //     }
            //   });
            // }
          } else {
            this.$message.error("提交失败，请稍后再试");
          }
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
          console.log("接口请求出错:", error);
        });
    },

    // 处理表格行点击事件(同步到相应的输入框中)
    handleRowClick(row) {
      const crowno = this.cachedCrowno; // 获取缓存的行号信息
      const rowIndex = this.detailsList.findIndex((r) => r.crowno === crowno);
      console.log("rowIndex:", rowIndex);

      if (rowIndex !== -1) {
        const status = this.NccStatusOptions.find(
          (option) => option.label === row.SkuState
        );
        console.log("status:", status);
        // 将 row 中的数据映射到 detailsList 中对应行的各个字段
        this.detailsList[rowIndex].pk_batchcode = row.pk_batchcode;
        this.detailsList[rowIndex].cwarehouseid = row.cwarehouse_id;
        this.detailsList[rowIndex].cstateid = status ? status.value : "";
        this.detailsList[rowIndex].vbatchcode = row.vbatchcode;
        this.detailsList[rowIndex].vvendbatchcode = row.vvendbatchcode;
        this.detailsList[rowIndex].vbcdef2 = row.vbcdef2;
        this.detailsList[rowIndex].vbcdef3 = row.vbcdef3 || "";
        // this.detailsList[rowIndex].dproducedate = row.pd_date;
        // this.detailsList[rowIndex].dvalidate = row.exp_date;
        // this.detailsList[rowIndex].vbdef48 = row.retest_date;
        this.detailsList[rowIndex].parent_class_id = row.parent_class_id;
        this.detailsList[rowIndex].sto_id = row.sto_id;
        this.detailsList[rowIndex].stu_class_id = row.stu_class_id;

        // 检查日期是否为 1900-01-01 00:00:00
        // 处理生产日期
        if (row.pd_date === "1900-01-01 00:00:00") {
          this.detailsList[rowIndex].dproducedate = "";
        } else {
          this.detailsList[rowIndex].dproducedate = row.pd_date;
        }

        // 处理有效期
        if (row.exp_date === "1900-01-01 00:00:00") {
          this.detailsList[rowIndex].dvalidate = "";
        } else {
          this.detailsList[rowIndex].dvalidate = row.exp_date;
        }

        // 处理复验期
        if (row.retest_date === "1900-01-01 00:00:00") {
          this.detailsList[rowIndex].vbdef48 = "";
        } else {
          this.detailsList[rowIndex].vbdef48 = row.retest_date;
        }

        // 更新 headerList.cwarehouseid
        this.$set(
          this.headerList,
          "cwarehouseid",
          this.detailsList[rowIndex].cwarehouseid
        );

        // 强制更新视图，确保数据变化反映到页面上
        this.$forceUpdate();

        // 关闭展开栏
        if (this.$refs.mainTable) {
          this.$refs.mainTable.toggleRowExpansion(
            this.detailsList[rowIndex],
            false
          );
        }
      }
    },

    // 1、获取NCC仓库信息
    searchNCCStockList() {
      this.loading = true;
      SearchSelect.searchNCCStockList(this)
        .then(() => {
          // 获取到仓库信息后，更新 NccStockOptions
          this.NccStockOptions = this.NccStockList.map((item) => ({
            label: item.label,
            value: item.value,
          }));
          console.log("获取到仓库信息", this.NccStockOptions);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 2、获取NCC库存状态信息
    searchNCCStockStatusList() {
      this.loading = true;
      SearchSelect.searchNCCStockStatusList(this)
        .then(() => {
          // 获取NCC库存状态信息后，更新 NccStatusOptions
          this.NccStatusOptions = this.NccStatusList.map((item) => ({
            label: item.label,
            value: item.value,
          }));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 重置
    resetForm() {
      // 先调用原本的resetFields方法重置常规表单部分
      this.$refs["elDialogForm"].resetFields();

      // 手动重置detailsList中相关数据
      this.detailsList.forEach((row) => {
        // row.nnum = ''; // 重置实收主数量
        row.vbdef50 = ""; // 重置容器
        row.cstateid = ""; // 重置库存状态
        row.vvendbatchcode = ""; // 重置供应商批号
        row.vbatchcode = ""; // 重置批号
        row.dproducedate = ""; // 重置生产日期
        row.dvalidate = ""; // 重置有效期
        row.vbdef48 = ""; // 重置复验期
        row.vbdef49 = ""; // 重置货架期
      });
    },
  },
};
</script>
<style scoped>
/* 整体信息行的flex布局样式 */
.info-row {
  display: flex;
  flex-wrap: wrap;
  padding: 0 0 0 50px;
}

/* 单个信息项的样式 */
.info-item {
  margin-bottom: 10px;
  padding: 5px;
  width: 100%;
  font-size: 15px;
}

.info-item > span:first-child {
  font-weight: 600;
}

.info-item span:nth-child(2) {
  font-weight: 500;
}
</style>
<style scoped>
.footer-global {
  border-top: 1px solid silver;
  position: fixed;
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  right: 0;
  bottom: 0;
  box-shadow: -1px 0 12px 0 var(--gray-5);
  transition: all 0.28s;
  background-color: #fff;
  z-index: 200;
  left: 0;
  height: 50px;
  margin-bottom: 0 !important;
}

.btn-box {
  width: calc(100% - 200px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  float: right;
  padding: 50px;
}

.row-disabled {
  background-color: #f5f5f5;
  color: #949292;
}

/* 必填项红色标记 */
.mark-red {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: red;
  margin-right: 5px;
}

.mark-arrow {
  display: inline-block;
  width: 0;
  height: 0;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  /* 向右的小箭头，颜色为蓝色 */
  border-left: 10px solid #409eff;
  margin-right: 5px;
  /* 添加动画 */
  animation: slideArrow 1s infinite alternate ease-in-out;
}

@keyframes slideArrow {
  0% {
    transform: translateX(0);
    /* 初始位置 */
    opacity: 0.5;
  }

  100% {
    transform: translateX(8px);
    /* 向右滑动 8px */
    opacity: 1;
  }
}
</style>
